package com.laoye.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;

import com.laoye.Exception.exception.BaseException;
import com.laoye.easyBusinessApplication;
import com.laoye.service.AliyunOSSService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class AliyunOSSServiceImpl implements AliyunOSSService {

    // 从配置文件读取OSS参数
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    /**
     * 初始化OSS客户端
     */
    private OSS getOSSClient() {
        // 创建OSS客户端实例（新版推荐使用OSSClientBuilder）
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 上传文件到OSS
     */
    // 上传文件方法修改如下：
    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new BaseException(401,"上传文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();

        String key = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        OSS ossClient = getOSSClient(); // 手动获取客户端
        try (InputStream inputStream = file.getInputStream()) {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            metadata.setContentType(file.getContentType());
            metadata.setCacheControl("max-age=31536000");

            ossClient.putObject(bucketName, key, inputStream, metadata);

            return "https://" + bucketName + "." + endpoint + "/" + key;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown(); // 手动关闭客户端
            }
        }
    }


    /**
     * 从OSS删除文件
     */
// 删除文件方法修改如下：
    @Override
    public boolean deleteFile(String fileUrl) {
        String host = "https://" + bucketName + "." + endpoint + "/";
        String key = fileUrl.replace(host, "");

        OSS ossClient = getOSSClient();
        try {
            if (ossClient.doesObjectExist(bucketName, key)) {
                ossClient.deleteObject(bucketName, key);
                return true;
            }
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown(); // 手动关闭客户端
            }
        }
    }

    /**
     * 获取文件列表
     */

    @Override
    public List<String> getFileUrls() throws Exception {
        List<String> fileUrls = new ArrayList<>();
        OSS ossClient = getOSSClient();
        ListObjectsRequest request = new ListObjectsRequest(bucketName);
        request.setMaxKeys(1000);
        ObjectListing objectListing = ossClient.listObjects(request);
        for(OSSObjectSummary objectSummary:objectListing.getObjectSummaries()){
            fileUrls.add(objectSummary.getKey());
        }
        return fileUrls;
    }
    public  void deleteList(List<String> fileUrls){
        DeleteObjectsRequest request = new DeleteObjectsRequest(bucketName);
        request.setKeys(fileUrls);
    }
}
